<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-button type="primary">添加角色</el-button>
      <!-- 权限列表 -->
      <el-table :data="rolesList" border style="width: 100%">
        <!-- 拓展列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item, index) in scope.row.children"
              :key="item.id"
              :class="['bdBottom', index == 0 ? 'bdTop' : '', 'alignCenter']"
            >
              <!-- 一级权限 -->
              <el-col :span="4"
                ><el-tag
                  closable
                  @close="removeRightById(scope.row, item.id)"
                  >{{ item.authName }}</el-tag
                ><i class="el-icon-caret-right"></i
              ></el-col>
              <!-- 二级及三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(subitem, index) in item.children"
                  :key="subitem.id"
                  :class="[index == 0 ? '' : 'bdTop', 'alignCenter']"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6"
                    ><el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, subitem.id)"
                      >{{ subitem.authName }}</el-tag
                    ><i class="el-icon-caret-right"></i
                  ></el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18"
                    ><el-tag
                      v-for="enditem in subitem.children"
                      :key="enditem.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, enditem.id)"
                      >{{ enditem.authName }}</el-tag
                    ></el-col
                  >
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="序号"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" icon="el-icon-delete"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="openRigtSettingDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 权限分配对话框 -->
    <el-dialog
      title="权限分配"
      :visible.sync="rightSettingDialogVisible"
      width="30%"
      @close="setRightDialogClosed"
    >
      <el-tree ref="rightTree" :data="rightsList" :props="treeProps" default-expand-all show-checkbox node-key="id" :default-checked-keys="rights"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightSettingDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="rightSettingDialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //角色列表
      rolesList: [],
      //是否打开权限分配对话框标志位
      rightSettingDialogVisible: false,
      //所有权限列表
      rightsList: [],
      //树结构设置
      treeProps:{
        children: 'children',
        label: 'authName'
      },
      //存放当前打开权限管理的所在行角色的三级权限
      rights: [],
      //记录当前打开权限管理所在行的角色ID
      roleID: ''
    };
  },
  created() {
    this.queryRolesList();
  },
  methods: {
    //获取角色列表
    queryRolesList: async function () {
      const { data: res } = await this.$http.get("/roles");
      if (res.meta.status != 200)
        return this.$message.error("角色列表获取失败");
      this.rolesList = res.data;
    },
    //根据ID删除角色权限
    removeRightById: async function (role, id) {
      //弹出对话框确认删除
      const confirmRes = await this.$confirm(
        "此操作将删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmRes == "cancel") return this.$message.info("已取消删除");
      //发送请求删除权限
      const { data: res } = await this.$http.delete(
        `/roles/${role.id}/rights/${id}`
      );
      if (res.meta.status != 200) return this.$message.error("删除失败");
      //返回值为最新该角色下的权限
      role.children = res.data;
    },
    //打开分配权限对话框
    openRigtSettingDialog: async function (role) {
      this.rightSettingDialogVisible = true;
      this.getRights(role, this.rights)
      //获取所有权限列表
      const { data: res } = await this.$http.get('/rights/tree')
      this.rightsList = res.data;
      //记录下当前打开权限管理角色的ID
      this.roleID = role.id
    },
    //递归找到对应角色的三级权限
    getRights: function(node, arr){
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(element => {
        this.getRights(element, arr)
      });
    },
    //监听权限分配对话框的关闭事件
    setRightDialogClosed: async function(){
      console.log(666);
      //清除权限选中列表
      this.rights = [];
      //获取权限分配树中选中的权限ID
      const checkedKeys = this.$refs.rightTree.getCheckedKeys();
      //获取权限分配树中半选中的权限ID
      const halfcheckedKeys = this.$refs.rightTree.getHalfCheckedKeys();
      //拼接所有选中/班选中权限的ID
      const rids = [
        ...checkedKeys,
        ...halfcheckedKeys
      ]
      const ridsStr = rids.join(',')
      //发送请求，修改角色权限
      const { data: res } = await this.$http.post(`/roles/${this.roleID}/rights`,{
        rids: ridsStr
      })
      if(res.meta.status != 200) return this.$message.error('权限分配失败')
      this.$message.success('权限分配成功！')
      this.queryRolesList()
    }
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdTop {
  border-top: 1px solid #eee;
}

.bdBottom {
  border-bottom: 1px solid #eee;
}

.alignCenter {
  display: flex;
  align-items: center;
}
</style>